package com.zxg.androidbuslearn

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Rect
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import android.media.Image
import android.nfc.Tag
import android.os.Bundle
import android.support.v7.widget.*
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView

/**
 * 作者: 赵小刚
 * 生成时间: 2018/10/29.
 * 版本: 1.0
 * 简介:
 * 修改记录:
 */
class RecyclerViewActivity : BaseActivity() {

    var TAG = "RecyclerViewActivity"
    lateinit var mRecyclerView: RecyclerView
    var items = arrayListOf<String>(
            "fitXY", "fitStart", "fitCenter", "fitEnd",
            "center", "centerCrop", "centerInside", "matrix"
    )

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.recycler_view)
        // 找到RecyclerView控件
        mRecyclerView = findViewById<RecyclerView>(R.id.recyclerView)
        // 设置LayoutManager
        // 网格布局
        mRecyclerView.layoutManager = GridLayoutManager(this, 3)
//        // 纵向布局
//        mRecyclerView.layoutManager = LinearLayoutManager(this) // 默认为纵向布局
//        mRecyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
//        // 横向布局
//        mRecyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
//        // 瀑布流布局
//        mRecyclerView.layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
        // 设置分隔线
        // 自定义复杂的分割线
        mRecyclerView.addItemDecoration(GridItemDecoration(this, 5, Color.RED))
//        // 上下的纵向分割线
//        mRecyclerView.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.VERTICAL))
//        // 左右的横向分割线
//        mRecyclerView.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.HORIZONTAL))
        // 设置Adapter，添加数据
        val imageAdapter = ImageAdapter(items)
        mRecyclerView.adapter = imageAdapter
        // 设置点击事件
        imageAdapter.setOnItemClickListener(onItemClickListener = object : ImageAdapter.OnItemClickListener {
            override fun onItemClick(view: View, position: Int) {
                LogUtil.logE(TAG, "点击了item -- " + position)
            }
        })
    }

}

class ImageAdapter : RecyclerView.Adapter<ImageAdapter.ViewHolder> {

    private var list: ArrayList<String> ?= null
    private var onItemClickListener: OnItemClickListener ?= null

    constructor(items: ArrayList<String>): super() {
        this.list = items
    }

    fun setOnItemClickListener(onItemClickListener: OnItemClickListener) {
        this.onItemClickListener = onItemClickListener
    }

    override fun getItemViewType(position: Int): Int {
        // TODO 设置显示不同类型时的ViewType
        return super.getItemViewType(position)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.recycler_item, parent, false)
        // TODO 更加不同类型的ViewType 返回不同的ViewHolder
        return ViewHolder(view)
    }

    override fun getItemCount(): Int {
        return this.list?.size as Int
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item = list?.get(position)
        holder.textView.text = item
        when (item) {
            "fitXY" -> { holder.imageView.scaleType = ImageView.ScaleType.FIT_XY }
            "fitStart" -> holder.imageView.scaleType = ImageView.ScaleType.FIT_START
            "fitCenter" -> holder.imageView.scaleType = ImageView.ScaleType.FIT_CENTER
            "fitEnd" -> holder.imageView.scaleType = ImageView.ScaleType.FIT_END
            "center" -> holder.imageView.scaleType = ImageView.ScaleType.CENTER
            "centerCrop" -> holder.imageView.scaleType = ImageView.ScaleType.CENTER_CROP
            "centerInside" -> holder.imageView.scaleType = ImageView.ScaleType.CENTER_INSIDE
            "matrix" -> holder.imageView.scaleType = ImageView.ScaleType.MATRIX
        }
        // 设置点击事件的回调
        if (onItemClickListener != null) {
            holder.itemView.setOnClickListener() {
                onItemClickListener?.onItemClick(holder.itemView, position)
            }
        }
        // 通用点击事件也可以写在这里，不放到回调里面
    }

    class ViewHolder: RecyclerView.ViewHolder {
        var imageView: ImageView
        var textView: TextView

        constructor(view: View) : super(view) {
            this.imageView = view.findViewById(R.id.itemImage) as ImageView
            this.textView = view.findViewById(R.id.itemText) as TextView
        }
    }

    interface OnItemClickListener {
        fun onItemClick(view: View, position: Int)
    }
}

// TODO: 不太好。要优化
class GridItemDecoration: RecyclerView.ItemDecoration {
    private var divider: Drawable? = null
    private var dividerWidth = 1

    constructor(context: Context, dividerWidth: Int, dividerColor: Int) {
        this.dividerWidth = dividerWidth
        divider = ColorDrawable(dividerColor)
    }

    override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
        drawHorizontal(c, parent)
        drawVertical(c, parent)
    }

    // 绘制水平分割线
    private fun drawHorizontal(canvas: Canvas, parent: RecyclerView) {
        val childCount = parent.childCount
        for (i in 0 until childCount) {
            val child = parent.getChildAt(i)
            val params = child.layoutParams as RecyclerView.LayoutParams
            val left = child.left - params.leftMargin
            val right = child.right - params.rightMargin
            val top = child.top - params.topMargin
            var bottom = top - dividerWidth
            if (isLastRow(parent, i, childCount)) {
                bottom = top
            }
            divider!!.setBounds(left, top, right, bottom)
            divider!!.draw(canvas)
        }
    }

    // 绘制垂直分割线
    fun drawVertical(canvas: Canvas, parent: RecyclerView) {
        val childCount = parent.childCount
        for (i in 0 until childCount) {
            val child = parent.getChildAt(i)
            val params = child.layoutParams as RecyclerView.LayoutParams
            var top = child.top - params.topMargin
            var bottom = child.bottom + params.bottomMargin + dividerWidth
            var left = child.right + params.rightMargin
            var right = left + dividerWidth
            divider!!.setBounds(left, top, right, bottom)
            divider!!.draw(canvas)
        }
    }

    // 判断是否是最后一行
    private fun isLastRow(parent: RecyclerView, position: Int, childCount: Int): Boolean {
        var childCount = childCount
        val layoutManager = parent.layoutManager
        if (layoutManager is GridLayoutManager) {
            val ranger = childCount % layoutManager.spanCount
            if (ranger == 0) {
                childCount = layoutManager.spanCount
            } else {
                childCount = childCount - ranger
            }
            if (position >= childCount) // 如果是最后一行，则不需要绘制底部
                return true
        }
        return false
    }

    override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
        super.getItemOffsets(outRect, view, parent, state)
        outRect!!.set(0, 0, divider!!.getIntrinsicWidth(), divider!!.getIntrinsicHeight());
    }

}
